package com.explorer.ider.bootguide.utils;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.util.List;

/**
 * Created by Eric on 2016/9/5.
 */
public class WifiConnectUtils {

    WifiManager wifiManager;
    List<ScanResult> mWifiList;
    WifiInfo mWifiInfo;



    //定义几种加密方式，一种是WEP，一种是WPA，还有没有密码的情况
    public enum WifiCipherType
    {
        WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
    }

    /**
     *构造函数mWifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
     */
    public WifiConnectUtils(WifiManager wifiManager)
    {
        this.wifiManager = wifiManager;
    }

    /**
     * 获取wifi信息
     */
    public WifiInfo getWifiInfo(){
        mWifiInfo = wifiManager.getConnectionInfo();
        return mWifiInfo;
    }

    /**
     * 获取Wifi信号
     */
    public int[] getWifiLevel(){
        int[] j = new int[mWifiList.size()];
        for (int i = 0; i < mWifiList.size(); i++) {
            j[i] = WifiManager.calculateSignalLevel(mWifiList.get(i).level,150);

        }

        return j;
    }

    /**
     * 是否打开wifi
     */
    public boolean checkWifi(){
        return  wifiManager.isWifiEnabled();
    }

    /**
     *打开wifi功能
     */
    public boolean openWifi()
    {
        boolean bRet = true;
        if (!wifiManager.isWifiEnabled())
        {
            bRet = wifiManager.setWifiEnabled(true);
        }
        return bRet;
    }
    //关闭wifi功能
    public boolean closeWifi()
    {
        boolean bRet = false;
        if (wifiManager.isWifiEnabled())
        {
            bRet = wifiManager.setWifiEnabled(false);
        }
        return bRet;
    }

    //搜索wifi设备
    public List<ScanResult> searchWifi(){
        if(!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.startScan();
        mWifiList = wifiManager.getScanResults();
        Log.i("wifishuliang", "searchWifi: " + mWifiList.size());
        return mWifiList;
    }



    /**
     * 提供一个外部接口，传入要连接的无线网
     *
     */
    public boolean connect(String SSID, String Password, WifiCipherType Type)
    {
        getWifiInfo();
        if(!this.openWifi()) {

        }else {
//            wifiManager.disconnect();
        }
        //开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右)，所以要等到wifi
        //状态变成WIFI_STATE_ENABLED 的时候才能执行下面的语句
        //WifiManager.WIFI_STATE_ENABLING 2
        //WifiManager.WIFI_STATE_ENABLED 3
       Log.d("----","wifiManager.getWifiState()" + wifiManager.getWifiState());
        while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING )
        {
            Log.d("-----","wifiManager.getWifiState" + wifiManager.getWifiState());
            try{
                //为了避免程序一直while循环，让它睡个100毫秒在检测……
                Thread.currentThread();
                Thread.sleep(100);
            }
            catch(InterruptedException ie){
            }
        }

        WifiConfiguration wifiConfig = this.createWifiInfo(SSID, Password, Type);
        //
        if(wifiConfig == null)
        {
            return false;
        }

        WifiConfiguration tempConfig = this.isExsits(SSID);

        if(tempConfig != null)
        {
            wifiManager.removeNetwork(tempConfig.networkId);
        }

        int netID = wifiManager.addNetwork(wifiConfig);
        boolean addSucess = wifiManager.enableNetwork(netID, true);
        boolean flag=false;
        boolean isSuccess=false;
//        if (addSucess) {
//            while (!flag && !isSuccess) {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e1) {
//                    e1.printStackTrace();
//                }
//                String currSSID = getCurrentWifiInfo().getSSID();
//                if (currSSID != null)
//                    currSSID = currSSID.replace("\"", "");
//                int currIp = getCurrentWifiInfo().getIpAddress();
//                if (currSSID != null && currSSID.equals(SSID) && currIp != 0) {
//                    isSuccess = true;
//                } else {
//                    flag = true;
//                }
//            }
//        }
        return addSucess;
    }


        /**   * 获取当前手机所连接的wifi信息   */
        public WifiInfo getCurrentWifiInfo() {


            return wifiManager.getConnectionInfo();
        }

    //查看以前是否也配置过这个网络
    private WifiConfiguration isExsits(String SSID)
    {
        List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs)
        {
            if (existingConfig.SSID.equals("\""+SSID+"\""))
            {
                return existingConfig;
            }
        }
        return null;
    }

    private WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type)
    {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if(Type == WifiCipherType.WIFICIPHER_NOPASS)
        {
            config.wepKeys[0] = "\"" + "\"";;
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;

            //或者下面两段代码也可以
            // config.hiddenSSID = true;
            // config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        }
        else if(Type == WifiCipherType.WIFICIPHER_WEP)
        {
            config.wepKeys[0] = "\""+Password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        else if(Type == WifiCipherType.WIFICIPHER_WPA)
        {
            config.preSharedKey = "\""+Password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); //这句好像不行
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        else
        {
            return null;
        }
        return config;
    }

}
